const db = require("../server/db.js");

module.exports = {
  async batchAdd(userId, productId, quantity) {
    console.log(userId, productId, quantity);
    const connection = await db.getConnection();
    try {
      await connection.beginTransaction();
      // 检查商品是否存在和库存
      const [product] = await connection.query(
        "SELECT product_id, price, stock FROM products WHERE product_id = ? AND status = 1",
        [productId]
      );

      if (!product.length) {
        throw new Error("商品不存在或已下架");
      }

      if (product[0].stock < quantity) {
        throw new Error("库存不足");
      }

      // 检查是否已存在购物车记录
      const [existing] = await connection.query(
        "SELECT id, quantity FROM cart WHERE user_id = ? AND product_id = ?",
        [userId, productId]
      );

      if (existing.length > 0) {
        // 更新数量
        const newQuantity = existing[0].quantity + quantity;
        await connection.query("UPDATE cart SET quantity = ? WHERE id = ?", [
          newQuantity,
          existing[0].id,
        ]);
      } else {
        // 新增记录
        await connection.query(
          "INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?)",
          [userId, productId, quantity]
        );
      }

      await connection.commit();
      return { success: true };
    } catch (error) {
      console.error("查询错误:", error);
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
      console.log("数据库连接已释放");
    }
  },
  // 获取购物车列表
  async getCartList(userId) {
    try {
      const rows = await db.query(
        `
          SELECT 
            c.id AS cart_id,
            c.quantity,
            c.selected,
            p.product_id,  -- 使用正确的列名
            p.name,
            p.price,
            p.image,
            p.stock,
            (p.price * c.quantity) AS subtotal
          FROM 
            cart c
            INNER JOIN products p ON c.product_id = p.product_id  -- 修正连接条件
          WHERE 
            c.user_id = ?
            AND p.status = 1
          ORDER BY 
            c.updated_at DESC;
    `,
        [userId]
      );

      return rows;
    } catch (error) {
      console.error("查询错误:", error);
      return error;
    } finally {
      connection.release();
      console.log("数据库连接已释放");
    }
  },
};
